package com.example.taluo.service;

import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class MatchmakingService {
    private final Queue<Integer> matchmakingQueue = new LinkedList<>(); // 匹配队列
    private final ConcurrentHashMap<Integer, Integer> matchedPlayers = new ConcurrentHashMap<>(); // 记录匹配成功的玩家和游戏ID
    private static int gameIdCounter = 1;

    public synchronized void joinQueue(Integer playerId) { // 加入匹配队列
        if (!matchmakingQueue.contains(playerId)) {
            matchmakingQueue.add(playerId);
        }
        System.out.println("加入匹配队列：" + playerId);
        System.out.println("匹配队列：" + matchmakingQueue.toString());
        matchPlayers();
    }

    private synchronized void matchPlayers() { // 匹配玩家
        while (matchmakingQueue.size() >= 2) {
            Integer player1 = matchmakingQueue.poll();
            Integer player2 = matchmakingQueue.poll();
            int gameId = gameIdCounter++;
            matchedPlayers.put(player1, gameId);
            matchedPlayers.put(player2, gameId);
        }
    }

    public Integer checkMatchStatus(Integer playerId) { // 查询匹配状态
        return matchedPlayers.get(playerId);
    }
}
